// ChatDisplayArea.js - 基于ChatDisplayArea.vue转换为纯JavaScript组件

export default {
  name: 'ChatDisplayArea',
  props: {
    chatHistory: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  setup(props) {
    // 配置 marked.js
    if (window.marked) {
      const renderer = new window.marked.Renderer();
      // 自定义链接渲染，在新标签页打开
      renderer.link = (href, title, text) => {
        const titleAttr = title ? ` title="${title}"` : '';
        return `<a href="${href}"${titleAttr} target="_blank" rel="noopener noreferrer">${text}</a>`;
      };

      window.marked.setOptions({
        renderer: renderer,
        sanitize: true, // 注意：此选项在新版marked.js中可能已移除，推荐DOMPurify
        breaks: true    // 将单个换行符渲染为 <br>
      });
    }

    // Markdown 渲染函数
    function renderMarkdown(rawMarkdown) {
      if (window.marked && rawMarkdown) {
        return window.marked.parse(rawMarkdown);
      }
      return rawMarkdown; // 如果 marked 不可用或内容为空，返回原始内容
    }

    // formatTimestamp 函数现在是全局的 (window.formatDisplayTimestamp)
    // 我们将在返回对象中引用它，以便模板可以像以前一样使用它

    return {
      formatTimestamp: window.formatDisplayTimestamp, // 引用全局函数
      renderMarkdown
    };
  },
  template: `
    <div class="chat-display-area">
      <div v-if="chatHistory.length === 0" class="empty-chat-message">
        No messages yet.
      </div>
      <div v-else class="messages-container">
        <div v-for="message in chatHistory" :key="message.message_id" class="chat-message">
          <div>
            <strong>{{ message.sender_nickname }}:</strong> <div v-html="renderMarkdown(message.content)"></div>
          </div>
          <div class="message-meta">
            <span class="timestamp">{{ formatTimestamp(message.timestamp) }}</span>
            <span v-if="message.tags && message.tags.length > 0" class="tags">
              Tags: {{ message.tags.join(', ') }}
            </span>
          </div>
        </div>
      </div>
    </div>
  `
};